package com.example.chao.myphotosearch.model;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;

import com.bumptech.glide.Glide;
import com.example.chao.myphotosearch.PhotoSearchApp;
import com.example.chao.myphotosearch.bean.ImageJoy;
import com.example.chao.myphotosearch.bean.SosoImage;
import com.example.chao.myphotosearch.config.API;
import com.example.chao.myphotosearch.config.DBManger;
import com.example.chao.myphotosearch.config.MySql;
import com.example.chao.myphotosearch.bean.DownloadImg;
import com.example.chao.myphotosearch.utils.Utils;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.jude.utils.JUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by wenhuaijun on 2016/1/22 0022.
 */
public class SqlModel {

    public static final String imgPath = Utils.getSDPath() + "/MyPictures";
    public static final int hasDownLoaded = 1;
    public static final int error = -1;
    public static DBManger dbManger = new DBManger(PhotoSearchApp.getInstance());
    /*public static void downloadBitmap( Context context, String url) {
        getFrescoDownloadBitmap(context,url).subscribe(new BaseBitmapDataSubscriber() {
            @Override
            protected void onNewResultImpl(Bitmap bitmap) {
                getSaveBitmapObservable(bitmap);
            }


            @Override
            protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
                JUtils.Toast("下载图片失败");
            }
        }, CallerThreadExecutor.getInstance());
    }*/

    public static DBManger getDbManger(){
        return dbManger;
    }
    public static void getSaveBitmapObservable(final Context context, final SosoImage sosoImage) {
        Observable.just(sosoImage)
                .map(new Func1<SosoImage, SosoImage>() {
                    @Override
                    public SosoImage call(SosoImage sosoImage) {
                        String url = sosoImage.getLargeImg();
                        if(sosoImage instanceof ImageJoy){
                            url = ((ImageJoy) sosoImage).getSourceurl();
                        }
                        if (dbManger.isExisted(url, MySql.DOWN_LOAD_TABLE)) {
                            return null;
                        } else {
                            return sosoImage;
                        }
                    }
                })
                .subscribeOn(Schedulers.io())
                .map(new Func1<SosoImage, String>() {
                    @Override
                    public String call(SosoImage sosoImage) {
                        if (sosoImage != null) {
                            Bitmap bitmap = null;
                            String name = "/" + System.currentTimeMillis() + ".png";
                            File file = new File(imgPath);
                            if (!file.exists()) {
                                JUtils.Log("!file.exists()");
                                file.mkdir();
                            }
                            file = new File(imgPath + name);
                            try {
                                if(sosoImage instanceof ImageJoy){
                                    ImageJoy joy = (ImageJoy) sosoImage;
                                    bitmap = Glide.with(context).load(joy.getSourceurl())
                                            .asBitmap()
                                            .into(sosoImage.getWidth(), sosoImage.getHeight())
                                            .get();
                                }else {
                                    bitmap = Glide.with(context).load(sosoImage.getLargeImg())
                                            .asBitmap()
                                            .into(sosoImage.getWidth(), sosoImage.getHeight())
                                            .get();
                                }
                                if (file.createNewFile()) {
                                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                                    fileOutputStream.flush();
                                    fileOutputStream.close();
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                                return error + "";
                            } catch (ExecutionException e) {
                                e.printStackTrace();
                                return error + "";
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                                return error + "";
                            } catch (IOException e) {
                                e.printStackTrace();
                                return error + "";
                            }
                            return file.toString();
                        } else {
                            return hasDownLoaded + "";
                        }
                    }
                })
                .subscribeOn(Schedulers.io())
                .doOnNext(new Action1<String>() {
                    @Override
                    public void call(String path) {
                        if (path != error + "" && path != hasDownLoaded + "") {
                            DownloadImg img = null;
                            if(sosoImage instanceof ImageJoy){
                                ImageJoy joy = (ImageJoy) sosoImage;
                                img = new DownloadImg(path, joy.getSourceurl(), joy.getHeight(), joy.getWidth());
                            }else {
                                 img = new DownloadImg(path, sosoImage.getLargeImg(), sosoImage.getHeight(), sosoImage.getWidth());
                            }
                            dbManger.addHasDownLoad(img);
                        }
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        if (s == hasDownLoaded + "") {
                            JUtils.Toast("已经存过了哟~");
                        } else if (s == error + "") {
                            JUtils.Toast("未知错误~,请稍后再试");
                        } else {
                            JUtils.Toast("下载图片成功，已下载到SdCard的MyPictures目录里");
                        }
                    }
                })
                .subscribe();
    }

    //从数据库获取所有下载图片的信息
    public static  Observable<ArrayList<DownloadImg>> getDownloadImgs(final Context context){
        Observable<ArrayList<DownloadImg>> observable = Observable.just("").map(new Func1<String, ArrayList<DownloadImg>>() {
            @Override
            public ArrayList<DownloadImg> call(String s) {

                return dbManger.getDownLoadImgs();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
        return  observable;
    }
    //从download数据库中删除一个图片信息
    public static void deleteDownloadImgByname(Context context,String name){
        dbManger.deleteHasDownload(name);
    }
    //批量删除选中的已下载图片
    public static Observable<String> deleteDownloadImgs(final Context context, final ArrayList<DownloadImg> imgs){
        Observable<String> observable = Observable.just("")
                .map(new Func1<String,String>() {
                    @Override
                    public String call(String s) {
                        dbManger.deleteDownloadPictures(imgs);
                        return API.status.success+"";
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
        return observable;
    }

    //存收藏图片信息到数据库
    public static void addCollectImg(ImageJoy netImage){
        dbManger.addHasCollect(netImage);
    }
    //从collect数据库删除一张图片信息
    public static void deleteCollectImgByUrl(Context context,String largeUrl){
        dbManger.deleteHasCollect(largeUrl);
    }
    //批量删除选中的已下载图片
    public static Observable<String> deleteCollectImgs(final Context context, final ArrayList<ImageJoy> imgs){
        Observable<String> observable = Observable.just("")
                .map(new Func1<String, String>() {
                    @Override
                    public String call(String s) {
                        dbManger.deleteCollectPictures(imgs);
                        return API.status.success + "";
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
        return observable;
    }

    //从数据库获取所有收藏图片的信息
    public static Observable<ArrayList<ImageJoy>> getCollectImgs(final Context context){
        Observable<ArrayList<ImageJoy>> observable = Observable.just("").map(new Func1<String, ArrayList<ImageJoy>>() {
            @Override
            public ArrayList<ImageJoy> call(String s) {
                return dbManger.queryHasCollectImgs();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
        return observable;
    }

    public static DataSource<CloseableReference<CloseableImage>> getFrescoDownloadBitmap(Context context, String url) {
        ImageRequest imageRequest = ImageRequestBuilder
                .newBuilderWithSource(Uri.parse(url))
                .setProgressiveRenderingEnabled(true)
                .build();
        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        DataSource<CloseableReference<CloseableImage>>
                dataSource = imagePipeline.fetchDecodedImage(imageRequest, context);
        return dataSource;
    }

}
